<template>
  <FormRelationRender :nodes="nodes" :hasRelationArrow="hasRelationArrow">
    <CenterNode
      @editForm="editCenterForm" @addNew="addNew"
      :formDefinition="formDefinition"
      :title="formDefinition.formName" slot="centerNode"/>

    <template slot="node" slot-scope="{node}">
      <CommonNode @selectForm="formId => $emit('selectForm', formId)" :title="node.title" :node="node"></CommonNode>
    </template>

    <template slot="lineIcon" slot-scope="{node}">
      <LineIcon @click="() => $emit('editRelations', node.key)" :content="node.count + ''"/>
    </template>
  </FormRelationRender>
</template>
<script>
import FormRelationRender from '@comp/hhd/design/relation/FormRelationRender/FormRelationRender.vue';
import CommonNode from '@comp/hhd/design/relation/FormRelationRender/CommonNode.vue';
import CenterNode from '@comp/hhd/design/relation/FormRelationRender/CenterNode.vue';
import LineIcon from '@comp/hhd/design/relation/FormRelationRender/LineIcon.vue';
import {createProps} from '@/utils';
import {createFormDefinition} from '@comp/hhd/design/FormDesigner/types';

export default {
  name: 'FormRelationChart',
  components: {LineIcon, CenterNode, CommonNode, FormRelationRender},
  props: {
    formDefinition: createProps(Object, createFormDefinition),
  },
  data() {
    return {
      nodes: [],
    };
  },
  methods: {
    addNew() {
      this.$emit('addNew')
    },
    editCenterForm() {
      this.$emit('editForm', this.formDefinition.id);
    },
    hasRelationArrow({key: targetFormDefinitionId}) {
      let list = (this.formDefinition.relations || []).filter(item => item.relationTargetFormId === targetFormDefinitionId);
      return !!list.length;
    },
    getNodes() {
      let res = [], relations = this.formDefinition.relations || [];
      relations.forEach(relation => {
        let node = res.find(n => relation.relationTargetFormId === n.key);
        if (node) {
          node.count++;
        } else {
          res.push({
            key: relation.relationTargetFormId,
            title: relation.relationTargetFormName,
            count: 1,
          });
        }
      });
      this.nodes = res;
    },
  },
  watch: {
    formDefinition: {
      handler() {
        this.getNodes();
      },
      immediate: true,
    }
  }
};
</script>